﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.Schedule;

namespace MyFurion.Start
{
    /// <summary>
    /// 本地日志清除定时任务
    /// </summary>
    public class LogJob:IJob
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            //var nowTime = DateTime.Now; // 此时的时间未必是真实触发时间，因为还包含创建线程，初始化等等时间
            await Task.Run(() => 
            {
                var nowTime = context.OccurrenceTime;//获取正确的时间
                string dateStr = nowTime.ToString("yyyy-MM-dd");
                List<string> saveFiles = new();
                saveFiles.Add($"Error-{dateStr}");
                saveFiles.Add($"Information-{dateStr}");
                for (int i = 1; i <= 6; i++)
                {
                    string strDate = nowTime.AddDays(-i).ToString("yyyy-MM-dd");
                    string errorLog = $"Error-{strDate}";
                    string infoLog = $"Information-{strDate}";
                    saveFiles.Add(errorLog);
                    saveFiles.Add(infoLog);
                }
                string rootPath = "";//日志文件目录
#if DEBUG
                rootPath = Path.Combine(App.HostEnvironment.ContentRootPath, "Logs");
#else
                rootPath = Path.Combine(AppContext.BaseDirectory, "Logs");
#endif
                if (Directory.Exists(rootPath))
                {
                    var logFiles = Directory.GetFiles(rootPath).ToList();
                    foreach (string fileName in logFiles)
                    {
                        string fullName=Path.GetFileName(fileName);
                        int pipTimes = 0;
                        saveFiles.ForEach(item => { if (fullName.StartsWith(item)){ pipTimes++; } });
                        if (pipTimes==0&&File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                    }
                }
            });            
            //return Task.CompletedTask;
        }
    }
}
